/*
 * @lc app=leetcode.cn id=135 lang=cpp
 *
 * [135] 分发糖果
 */

// @lc code=start
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
    int candy(vector<int> &ratings)
    {
        if (ratings.size() == 1)
            return 1;
        const int N = ratings.size();
        vector<int> candies(0, N);

        int ret = 0;
        int l = 0, r = 1;

        { // 下降区间
            while (r < ratings.size() && ratings[l] > ratings[r])
            {
                ++r;
            }

            {
                // r-1 孩子分配一个糖果即可
                int need = 1;
                for(int i = r - 1; i > l; i--)
                {
                    candies[i] = need++;
                }

                if(l == 0) candies[l] = candies[l+1] + 1;
                else candies[l] = std::max(candies[l+1], candies[l-1]);
            }

            l = r;
            ++r;
        }



        return std::accumulate(candies.begin(), candies.end(), 0);
    }
};
// @lc code=end
